<template>
  <a-modal v-model:open="ShowModalFlag" title="选择商品" @cancel="hideModal" @ok="hideModal" width="60vw">
    <a-row :gutter="10">
      <a-col :span="4" style="margin-top: 10px">
        <CategoryTree ref="categoryTreeRef" v-model:value="company_cate_id" @update:value="() => queryData()" />
      </a-col>

      <a-col :span="20" style="background-color: #f8f8f8; padding: 20px; border-radius: 8px; overflow-y: auto">
        <!---------- 查询表单form begin ----------->
        <a-form class="smart-query-form" :model="queryForm">
          <a-form-item class="smart-query-form-item">
            <a-input v-model:value.trim="queryForm.goods_name" placeholder="商品名称" autofocus />
          </a-form-item>
          <a-form-item class="smart-query-form-item">
            <a-input v-model:value.trim="queryForm.no" placeholder="商品条码" />
          </a-form-item>
          <a-form-item class="smart-query-form-item">
            <BrandSelect v-model:value="queryForm.company_brand_id" placeholder="品牌" />
          </a-form-item>

          <a-form-item class="smart-query-form-item">
            <a-button-group>
              <a-button type="primary" html-type="submit" @click="onSearch">
                <template #icon>
                  <SearchOutlined />
                </template>
                查询
              </a-button>
              <a-button @click="resetQueryData">
                <template #icon>
                  <ReloadOutlined />
                </template>
                重置
              </a-button>
            </a-button-group>
          </a-form-item>
        </a-form>
        <!---------- 查询表单form end ----------->

        <a-table size="small" :dataSource="tableData" :columns="columns" :loading="tableLoading" rowKey="id" bordered :scroll="{ x: 'max-content', y: 350 }" :pagination="false" :showSorterTooltip="false" :row-selection="{ selectedRowKeys: selectedRowKeyList, onChange: onSelectChange, preserveSelectedRowKeys: true }">
          <template #bodyCell="{ text, record, column }">
            <template v-if="column.dataIndex === 'img'">
              <a-image :width="text ? 30 : 50" :src="text || failImg" />
            </template>
            <template v-if="column.dataIndex === 'barcode'">
              {{ _.find(record.spec, ['unit_type', record.default_unit_type])?.barcode }}
            </template>
            <template v-if="column.dataIndex === 'unit_name'">
              <a-radio-group v-model:value="record.default_unit_type" option-type="button" :options="_.map(record.spec, filterUnit)" />
            </template>
            <template v-if="column.dataIndex === 'spec_name'">
              {{ _.find(record.spec, ['unit_type', record.default_unit_type])?.spec_name }}
            </template>
            <template v-if="column.dataIndex === 'sale_price'">
              {{ _.find(record.spec, ['unit_type', record.default_unit_type])?.sale_price }}
            </template>
          </template>
        </a-table>
        <div class="smart-query-table-page">
          <a-pagination showSizeChanger showQuickJumper show-less-items :pageSizeOptions="PAGE_SIZE_OPTIONS" :defaultPageSize="queryForm.limit" v-model:current="queryForm.page" v-model:pageSize="queryForm.limit" :total="total" @change="queryData" @showSizeChange="queryData" :show-total="(total) => `共${total}条`" />
        </div>
      </a-col>
    </a-row>
    <template #footer>
      <a-button type="primary" @click="onSubmit" html-type="button">确定</a-button>
    </template>
  </a-modal>
</template>
<script setup lang="ts">
import _ from 'lodash'
import { message } from 'ant-design-vue'
import { useQuery } from '@/hooks/web/use-query-hook'
import { PAGE_SIZE_OPTIONS } from '@/constants/system/common-const'
import { searchApi } from '@/api/search/search-api'
import { QUERY_FORM_OP } from '@/constants/support/query-form-op-const'
import CategoryTree from '@/components/business/category-tree/index.vue'
import BrandSelect from '@/components/business/select/brand-select.vue'
import failImg from '@/assets/images/notice/failImg.png'
const emit = defineEmits(['confirm'])
const props = defineProps({
  disabled: {
    type: String
  }
})

// ---------------------------- 表格列 ----------------------------
const columns = ref([
  {
    title: '图片',
    dataIndex: 'img'
  },
  {
    title: '商品名称',
    dataIndex: 'goods_name'
  },
  {
    title: '商品编码',
    dataIndex: 'no'
  },
  {
    title: '单位',
    dataIndex: 'unit_name'
  },
  {
    title: '规格条码',
    dataIndex: 'barcode'
  },
  {
    title: '规格',
    dataIndex: 'spec_name',
    width: 100
  },
  {
    title: '单价',
    dataIndex: 'sale_price'
  }
])

// ---------------------------- 查询数据表单和方法 ----------------------------
const company_cate_id = ref(0)
const { queryForm, tableData, tableLoading, total, onSearch, resetQuery, queryData, setQuery } = useQuery({
  fetchDataApi: async (params) => {
    params.cate_id = company_cate_id.value
    const res = await searchApi.goodsList(params)
    return {
      list: res.data.data,
      total: res.data.total
    }
  },
  queryFormFilter: {
    goods_name: '',
    no: '',
    status: 1,
    company_brand_id: undefined
  },
  queryFormOp: {
    goods_name: QUERY_FORM_OP['模糊查询'],
    no: QUERY_FORM_OP['模糊查询'],
    status: QUERY_FORM_OP['全等查询'],
    company_brand_id: QUERY_FORM_OP['全等查询']
  }
})
// ---------------------------- 重置 ----------------------------
function resetQueryData() {
  queryForm.value = {
    page: 1,
    limit: 10
  }
  queryData()
}
onMounted(queryData)
// ---------------------------- 规格 ----------------------------
function filterUnit(specData) {
  return {
    label: specData.unit_name,
    value: specData.unit_type
  }
}

// 选择表格行
const selectedRowKeyList = ref<number[]>([])
const selectedRowList = ref<any[]>([])

function onSelectChange(selectedRowKeys: number[], selectedRows: any[]) {
  selectedRowKeyList.value = selectedRowKeys
  selectedRowList.value = selectedRows
}

const ShowModalFlag = ref(false)
function hideModal() {
  ShowModalFlag.value = false
  resetQuery(false)
  selectedRowList.value = []
  selectedRowKeyList.value = []
}
function showModal() {
  ShowModalFlag.value = true
}

function onSubmit() {
  let isStockEnough = true
  if (props.disabled == 'true') {
    selectedRowList.value.forEach((item) => {
      const specItem = item.spec.find((spec) => spec.unit_type === item.unit)
      if (specItem && Number(specItem.stock) === 0) {
        message.error(`${item.name}库存不足！`)
        isStockEnough = false
      }
    })
  }

  if (isStockEnough) {
    if (selectedRowList.value.length > 0) {
      emit('confirm', selectedRowList.value)
    }
    hideModal()
  }
}

defineExpose({
  showModal,
  hideModal
})
</script>

<style lang="less" scoped>
.smart-query-form {
  --grid-column-col: 4;
  padding-left: 0;
  padding-right: 0;
  background-color: #f8f8f8;
}
</style>
